<?php

namespace app\admin\controller\system;

use app\admin\controller\BaseController;
use app\admin\logic\system\SystemRegionLogic;
use app\admin\validate\system\SystemRegionValidate;
use support\Request;
use support\Response;

/**
 * 菜单控制器
 */
class SystemRegionController extends BaseController
{
    /**
     * 构造
     */
    public function __construct()
    {
        $this->logic = new SystemRegionLogic();
        $this->validate = new SystemRegionValidate();
        parent::__construct();
    }

    /**
     * 数据列表
     * @param Request $request
     * @return Response
     */
    public function index(Request $request) : Response
    {
        $where = $request->more([
            ['name', ''],
            ['parent_id', 0],
        ]);
        if (empty($where['parent_id'])) {
            $where['parent_id'] = 0;
        }
        $data = $this->logic->getList($this->logic->search($where));
        return $this->success($data);
    }
    
    public function getAllRegion(Request $request) : Response
    {
        $where = $request->more([
            ['name', ''],
            ['parent_id', 0],
        ]);
        $isTree = $request->input('tree', 'false');
        if ($isTree === 'true') {
            unset($where['parent_id']);
            return $this->success($this->logic->tree($where));
        }
        if (empty($where['parent_id'])) {
            $where['parent_id'] = 0;
        }
        $data = $this->logic->getAllRegion($where);
        foreach($data as &$item) {
            if ($item['level'] < 4)
                $item['hasChildren'] = $this->logic->search(['parent_id' => $item['id']])->count() > 0 ? 1 : 0;
            else
                $item['hasChildren'] = 0;
            
        }
        return $this->success($data);
    }

}